package com.myself.ssoserver.service

import org.slf4j.LoggerFactory
import org.springframework.mail.MailException
import org.springframework.mail.SimpleMailMessage
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Service
import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.Context

// EmailService.kt
@Service
open class EmailService(
    private val javaMailSender: JavaMailSender,
    private val templateEngine: TemplateEngine // Thymeleaf模板引擎
) {
    private val logger = LoggerFactory.getLogger(javaClass)

    // 发送简单文本邮件
    @Async
    open fun sendSimpleEmail(
        to: String,
        subject: String,
        text: String
    ) {
        try {
            val message = SimpleMailMessage().apply {
                setTo(to)
                setSubject(subject)
                setText(text)
                setFrom("noreply@example.com")
            }
            javaMailSender.send(message)
            logger.info("邮件已发送至: $to")
        } catch (ex: MailException) {
            logger.error("邮件发送失败: ${ex.message}")
            throw EmailException("邮件发送失败，请稍后重试")
        }
    }

    // 发送HTML模板邮件
    @Async
    open fun sendHtmlEmail(
        to: String,
        subject: String,
        template: String, // 模板文件名
        variables: Map<String, Any>
    ) {
        try {
            val context = Context().apply {
                variables.forEach { (k, v) -> setVariable(k, v) }
            }

            val htmlContent = templateEngine.process(template, context)

            val message = MimeMessageHelper(javaMailSender.createMimeMessage()).apply {
                setTo(to)
                setSubject(subject)
                setText(htmlContent, true)
                setFrom("noreply@example.com")
            }

            javaMailSender.send(message.mimeMessage)
        } catch (ex: Exception) {
            logger.error("HTML邮件发送失败: ${ex.stackTraceToString()}")
            throw EmailException("邮件发送失败")
        }
    }
}

// 自定义邮件异常
class EmailException(message: String) : RuntimeException(message)